<template>
  <div class="admin table-s">
    <div class="mt-2">
      <el-card v-loading="loding" class="mt-2 !border-none" shadow="never">
        <mtable
          :data="tableList"
          ref="clearSort"
          :highlightCurrentRow="false"
          :type="typeTable"
          :list="options.tableTile"
          :indexmao="indexmao"
          :rowtype="true"
          :bill="false"
          :operation="true"
          :tableheight="'385'"
          @handleAdds="handleAdds"
          @onsortchange="onsortchange"
          :defaultSort="{ prop: 'title', order: 'ascending' }"
          :toolwidth="80"
        >
          <template #tool="{ item }">
            <el-table-column
              v-if="item.display == 1"
              :label="item.name"
              show-overflow-tooltip
              :prop="item.value"
              :width="item.width"
            >
              <template #default="{ row }">
                <div v-if="item.name == '名称'">
                  <el-input
                    v-if="
                      !mode ||
                      disableds == '新增调拨单' ||
                      disableds == '新增入库单'
                    "
                    v-model="row.title"
                    @input="onshowtable(row)"
                    @focus="onfocus"
                    :disabled="disabledshow"
                    size="small"
                  >
                    <template #suffix>
                      <el-icon class="el-input__icon">
                        <MoreFilled
                          @click="onShowtables(row)"
                          style="cursor: pointer"
                        />
                      </el-icon>
                    </template>
                  </el-input>

                  <p
                    v-else
                    class="fontcolor"
                    style="cursor: pointer"
                    @click="onDetilPopup(row)"
                  >
                    {{ row.title }}
                  </p>
                </div>
                <div v-if="item.name == '数量'">
                  <div
                    class="flex"
                    v-if="
                      (row.category_id != 4) & !mode ||
                      (disableds == '新增调拨单') & (row.category_id != 4) ||
                      (disableds == '新增入库单') & (row.category_id != 4)
                    "
                  >
                    <el-input
                      v-if="row.category_id == 15 && levelType != 1"
                      v-model="row.unit_length"
                      class="flex-1"
                      :clearable="false"
                      @blur="onquantitying(row)"
                      size="small"
                    >
                      <template #append
                        >{{ row.unit_name_15 }}/{{ row.unit_name }}</template
                      >
                    </el-input>
                    <el-select
                      class="flex-1"
                      @change="onquantitying(row)"
                      v-if="row.category_id == 15 && levelType == 1"
                      style="width: 120px"
                      v-model="row.unit_length"
                      placeholder="Select"
                      size="small"
                    >
                      <el-option
                        v-for="item in row.sub"
                        :key="item.unit_length"
                        :label="
                          item.unit_length +
                          row.unit_name_15 +
                          '/' +
                          row.unit_name +
                          ' ' +
                          item.quantity +
                          row.unit_name
                        "
                        :value="item.unit_length"
                      />
                    </el-select>
                    <template v-if="row.category_id == 15 && levelType == 1"
                      >{{ row.unit_name_15 }}/{{ row.unit_name }}</template
                    >
                    <div
                      v-if="row.category_id == 15 && levelType != 1"
                      style="width: 10px; background-color: #fff"
                    ></div>
                    <el-input
                      v-model="row.quantity"
                      class="flex-1"
                      :clearable="false"
                      @blur="onquantity(row)"
                      size="small"
                    >
                      <template #append>{{ row.unit_name }}</template>
                    </el-input>
                  </div>
                  <div v-else class="fontcolor">
                    <div class="flex">
                      <div class="flex-1" v-if="row.category_id == 15">
                        {{ row.unit_length }}{{ row.unit_name_15 }}/{{
                          row.unit_name
                        }}
                      </div>
                      <div class="flex-1" style="margin-left: 10px">
                        {{ row.quantity }}{{ row.unit_name }}
                      </div>
                      <div
                        class="flex-1"
                        v-if="row.category_id == 15"
                        style="color: #409eff"
                      >
                        {{ (row.unit_length * row.quantity).toFixed(2)
                        }}{{ row.unit_name_15 }}
                      </div>
                    </div>
                  </div>
                </div>
                <div v-if="item.name == '总价(元)'">
                  <el-input
                    v-if="
                      (row.category_id != 4) & !mode ||
                      (disableds == '新增调拨单') & (row.category_id != 4) ||
                      (disableds == '新增入库单') & (row.category_id != 4)
                    "
                    v-model="row.total_price"
                    :clearable="true"
                    size="small"
                  >
                  </el-input>
                  <span v-else>{{ row.total_price }}</span>
                </div>
                <div v-if="item.name == '总重(千克)'">
                  <el-input
                    v-if="
                      (row.category_id != 4) & !mode ||
                      (disableds == '新增调拨单') & (row.category_id != 4) ||
                      (disableds == '新增入库单') & (row.category_id != 4)
                    "
                    v-model="row.cargo_weight"
                    :clearable="true"
                    size="small"
                  >
                  </el-input>
                  <span v-else>{{ row.cargo_weight }}</span>
                </div>
                <div v-if="item.name == '从属设备'">
                  <!-- <el-button
                    @click="onHovertitles(row)"
                    v-if="row.slave_name"
                    size="small"
                  >
                    {{ row.slave_name }}
                  </el-button> -->
                  <!-- <butstyle @onHovertitles="onHovertitles" :row="formData"></butstyle> -->
                  <butstyle
                    @onHovertitles="onHovertitles"
                    :row="row"
                  ></butstyle>
                </div>
                <div v-if="item.name == '物料分类'">
                  <span>{{
                    booktypefilter(row.cate_name, row.category_id)
                  }}</span>
                </div>
                <div
                  v-if="
                    item.name == '库存数量' &&
                    row.category_id == 15 &&
                    levelType == 1
                  "
                >
                  <span v-if="numshow">
                    <span>{{ booktypefilters(row.sub, row.unit_length) }}</span>
                    <span v-if="row.unit_length">{{ row.unit_name }}</span>
                  </span>
                  <span v-else-if="mode"
                    >{{ row.quantity_num }}{{ row.unit_name_15 }}</span
                  >
                  <span v-else></span>
                </div>
                <div
                  v-if="
                    item.name == '库存数量' &&
                    row.category_id == 15 &&
                    levelType != 1
                  "
                >
                  <span v-if="numshow">
                    <span>{{ row.quantity_num }}</span>
                    <span v-if="row.quantity_num">{{ row.unit_name_15 }}</span>
                  </span>
                  <span v-else></span>
                </div>
                <div v-if="item.name == '库存数量' && row.category_id != 15">
                  <span>{{ row.quantity_num }}{{ row.unit_name }}</span>
                </div>
              </template>
            </el-table-column>
          </template>
          <template
            #operation="{ row }"
            v-if="
              !mode || disableds == '新增调拨单' || disableds == '新增入库单'
            "
          >
            <el-button type="danger" link @click="handleDelete(row)">
              删除
            </el-button>
            <!-- <el-switch v-model="row.typeShow" size="small" active-text="删除" inactive-text="增加" /> -->
            <el-button type="primary" link @click="onAddItem(row)">
              添加
            </el-button>
          </template>
        </mtable>
      </el-card>
    </div>
    <el-button
      v-if="tableList.length == 0"
      class="mt-4"
      style="width: 100%"
      @click="onAddItem"
    >
      增加
    </el-button>
  </div>
  <div class="tableing" v-if="showTable">
    <div style="padding: 10px">
      <div style="height: 510px">
        <hovertable
          :tableLists="tableLists"
          :popupTitle="popupTitle"
          @onsuccess="onsuccessing"
          @onSelectionchange="onSelectionchange"
          @rowClickFunc="rowClickFunc"
          :typeTable2="typeTable2"
        >
        </hovertable>
      </div>
      <div style="display: flex; justify-content: end; padding-top: 20px">
        <el-button @click="oncolse">取消</el-button>
        <el-button type="primary" @click="onsum">确认</el-button>
      </div>
    </div>
  </div>
  <div class="tableshow" v-if="tableshow">
    <div style="height: 10px"></div>
    <mcommodityList @onCancel="tableshow = false" @onsumTable="onsumTable" />
  </div>
  <tableHover
    v-if="Hovertitles"
    :showImage="true"
    ref="HovertitleRefs"
    @success="getLists"
    @close="Hovertitles = false"
  />
  <EdittablePopup
    v-if="showTables"
    ref="editRefs"
    :type="typeTable"
    @success="getOptions"
    @close="showTables = false"
  />
  <detilPopup
    :show="DetilPopupShow"
    :title="DetilPopup"
    :type="10"
    :list="DetilPopupList"
    @handleClose="DetilPopupShow = false"
  ></detilPopup>
</template>

<script lang="ts" setup>
import detilPopup from "@/components/detilPopup.vue";
import tableHover from "@/components/table-hovers/index.vue";
import { usePaging } from "@/hooks/usePagings";
import mtable from "@/components/table/index.vue";
import hovertable from "./hovertable.vue";
import feedback from "@/utils/feedback";
import mcommodityList from "./commodityList.vue";
import { adminLists, admindetail } from "@/api/materials/product";
import EdittablePopup from "@/components/settable/index.vue";
import { adminListss, orderDataDelete } from "@/api/inventory/list";
import { adminListPopup } from "@/api/water/list";
import { tableListing } from "@/utils/tableData";
import { getCommonFieldDisplay } from "@/api/tools/code";
import useAppStore from "@/stores/modules/inventory";
import butstyle from '@/components/butstyle.vue';
const emit = defineEmits(["onShowtables", "onfocus"]);
const props = defineProps([
  "warehouse_id",
  "tableName",
  "disableds",
  "type_name",
  "mode",
  "popupTitle",
  "type",
  "levelType",
]);

const userStore = useAppStore();
const popupTitle = computed(() => userStore.popupTitle);
const tableList = computed(() => userStore.tableList);
const indexmao = computed(() => userStore.indexmao);
const typeing = computed(() => userStore.typeing);
const numshow = computed(() => userStore.numshow);
const showTables = ref(false);
const tableLists = ref([]);
const showTable = ref(false);
const tableshow = ref(false);
const HovertitleRefs = shallowRef<InstanceType<typeof tableHover>>();
const editRefs = shallowRef<InstanceType<typeof EdittablePopup>>();
const outbound_warehouse_id = computed(() => userStore.warehouse_id);
const clearSort = shallowRef<InstanceType<typeof tableHover>>();
const disabledshow = ref(false);
const Hovertitles = ref(false);
const tableShowbut = ref(null);
watch(props, (newValue) => {
  formData.warehouse_id = newValue.warehouse_id;
});
const DetilPopupList = ref([]);
const DetilPopup = ref("详情");
const dataPopup = (id: any) => {
  admindetail({
    id: id,
  }).then((data: any) => {
  
    DetilPopupList.value = data;
  });
};
const DetilPopupShow = ref(false);
const onDetilPopup = (val: any) => {
  dataPopup(val.id);
  DetilPopupShow.value = true;
};
// 表单数据
const formData = reactive({
  title: "",
  warehouse_id: "",
  root: "",
  is_order: 1,
  filter_ids: [],
});
const typeTable = ref("add_inventory_10");

watch(outbound_warehouse_id, (newValue: any) => {
  if (newValue) {
    disabledshow.value = false;
  }
});
watch(
  tableList,
  (newValue: any) => {
    // console.log('newValue---0',newValue)
    formData.filter_ids = [];
    if (newValue) {
      newValue.find((val: any) => {
        if (val.cate_name) {
          if (val.cate_name[0].id == 4) {
            formData.filter_ids.push(val.id);
          }
        }
      });
    }
  },
  {
    deep: true,
  }
);

const onsortchange = (column: any) => {
  if (column.prop === "title" && column.order !== null) {
    let arr = [];
    tableList.value.map((item) => {
      item.title === null || item.title === ""
        ? arr.push(item)
        : arr.unshift(item);
    });
    userStore.tableListdata(arr);
  }
};
const onsuccessing = async () => {
  await getLists();
  tableLists.value = [];
  tableLists.value = pager.lists;
};

const handleAdds = async () => {
  showTables.value = true;
  await nextTick();
  editRefs.value?.open("add");
};

const onHovertitles = async (data: any) => {
  Hovertitles.value = true;
  await nextTick();
  HovertitleRefs.value?.open("edit");
  HovertitleRefs.value?.setFormData(data);
};
const booktypefilter = (list: any, id: any) => {
  if (list) {
    const obj = list.find((val: any) => val.id == id);
    return obj ? obj.name : null;
  }
};
const booktypefilters = (list: any, id: any) => {
  if (list) {
    const obj = list.find((val: any) => val.unit_length == id);
    return obj ? obj.quantity : null;
  }
};
const onquantity = (row: any) => {
  const ss = Math.sign(row.quantity);
  if (ss == -1) {
    feedback.msgError(`请输入正数`);
  } else {
    if (props.type == "入库单") {
    } else {
      if (row.quantity > parseInt(row.quantity_num) + parseInt(row.quantity)) {
        tableList.value[row.index].quantity = row.quantity_num;
        feedback.msgError(`数量不能超出库存数量`);
      }
    }
  }
};
const elestval = ref();
const indexval = ref();
const onquantitying = (row: any) => {
  userStore.tableListAddsings(tableList.value);
  elestval.value = row.unit_length;
  indexval.value = row.index;
  if (row.unit_length) {
    userStore.onnumshow(true);
    tableShowbut.value = row.index;
  }
};
const onfocus = () => {
  if (props.type == "入库单") {
  } else {
    if (popupTitle.value == "10") {
    } else {
      if (outbound_warehouse_id.value) {
      } else {
        emit("onfocus");
        feedback.msgError("请先填写出库入库仓库");
        disabledshow.value = true;
      }
    }
  }
};
const rowClickFunc = (row: any, ref: any) => {
  ref.toggleRowSelection(row);
};
const types = () => {
  if (typeing.value == "入库单") {
    return adminLists;
  } else {
    if (popupTitle.value == "20") {
      return adminListss;
    } else {
      return adminLists;
    }
  }
};

const { getLists, pager } = usePaging({
  fetchFun: types(),
  params: formData,
});
const oncolse = () => {
  showTable.value = false;
  userStore.tableListdatas(tbaleindex.value);
};
const tbaleindex = ref("");
const onsumTable = (val: any) => {
  tableshow.value = false;
  options.listall = val;
  userStore.tableListAddsing(options.listall, tbaleindex.value);
};
const options = reactive({
  listall: [] as any[],
  tableTile: [] as any[],
  tableTiles: [] as any[],
});
const onSelectionchange = (val: any) => {
  options.listall = val;
};
const loding = ref(true);
const getOptions = () => {
  getCommonFieldDisplay({
    type: typeTable.value,
  }).then((data: any) => {
    options.tableTile = data;
    loding.value = false;
  });
};

const onorderDataDelete = (id: any) => {
  orderDataDelete({
    id: id,
  }).then((data: any) => {});
};
const ontype = (rew: any) => {
  if (props.type_name !== "新增调拨单") {
    tbaleindex.value = rew.index;
    tableshow.value = true;
  } else {
    if (outbound_warehouse_id.value) {
      tbaleindex.value = rew.index;
      tableshow.value = true;
    } else {
      feedback.msgError("请先填写出库入库仓库");
    }
  }
};
const typeTable2 = ref("search_1");
const onSetType = () => {
  if (popupTitle.value == 10) {
    typeTable.value = "add_inventory_10";
    typeTable2.value = "search_1";
  } else if (popupTitle.value == 20) {
    if (typeing.value == "入库单") {
      typeTable2.value = "search_1";
      typeTable.value = "add_inventory_10";
    } else {
      typeTable.value = "add_inventory_20";
      typeTable2.value = "search_2";
    }
  }
};
const onShowtables = async (rew: any) => {
  emit("onShowtables");
  setTimeout(() => {
    ontype(rew);
  }, 100);
};
const onsum = async () => {
  if (JSON.stringify(options.listall) === "[]") {
    feedback.confirm("请选择商品");
  } else {
    userStore.tableListAddsing(options.listall, tbaleindex.value);
    showTable.value = false;
  }
};
const onAddItem = (index: any) => {
  const a = Math.floor(Math.random() * (100 - 1) + 1);
  const b = Math.floor(Math.random() * (100 - 1) + 1);
  userStore.tableListAdd(
    {
      product_id: `${a + b}s`,
      title: "",
      typeShow: false,
      quantity: 0,
      total_price: 0,
      cargo_weight: 0,
    },
    index
  );
};
const onshowtable = async (index: any) => {
  if (props.type_name !== "调拨单") {
    tbaleindex.value = index.index;
    formData.title = index.title;
    await getLists();
    tableLists.value = [];
    tableLists.value = pager.lists;
    showTable.value = true;
  } else {
    if (outbound_warehouse_id.value) {
      tbaleindex.value = index.index;
      formData.title = index.title;
      await getLists();
      tableLists.value = [];
      tableLists.value = pager.lists;
      showTable.value = true;
    } else {
      feedback.msgError("请先填写出库入库仓库");
    }
  }
};
const handleDelete = async (index: number) => {
  await feedback.confirm("确定要删除？");
  if (index.order_data_id) {
    onorderDataDelete(index.order_data_id);
  }
  userStore.tableListDel(index.index);
};
onMounted(() => {
  onSetType();
  getOptions();
  userStore.tableListdata(tableListing());
});
</script>
<style scoped lang="scss">
.tableing {
  width: 1250px;
  height: 600px;
  background-color: #fff;
  position: fixed;
  left: 50%;
  top: 50%;
  margin-left: -625px;
  margin-top: -300px;
  z-index: 999;
  padding: 10px;
  border: 1px solid rgba(#333, 0.2);
  border-radius: 5px;
}

.tableshow {
  width: 1250px;
  height: 600px;
  background-color: #fff;
  position: fixed;
  border-radius: 5px;
  padding: 10px 20px;
  left: 50%;
  top: 50%;
  margin-left: -625px;
  margin-top: -300px;
  z-index: 999;
  border: 1px solid rgba(#333, 0.2);
}
</style>
<style scoped lang="scss">
::v-deep .el-input.is-disabled .el-input__inner {
  background-color: #fff !important;
  color: #666666;
  cursor: not-allowed;
}

::v-deep .el-input__inner {
  border: 0;
}

::v-deep .el-input.is-disabled .el-input__wrapper {
  background-color: #fff !important;
}

::v-deep .el-image__error {
  background-color: #fff !important;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
  background-color: #fff !important;
  border-color: #fff !important;
  color: #666666;
  cursor: not-allowed;
}

.fontcolor {
  color: #666666;
}

::v-deep.el-table--large .el-table__cell {
  padding: 7px 0;
}

.table-s {
  ::v-deep .el-input__wrapper {
    box-shadow: 0 0 0 0px #fff inset;
  }
}

::v-deep .el-input-group__append,
.el-input-group__prepend {
  background-color: #fff;
  box-shadow: none;
  padding: 0 4px;
  white-space: nowrap;
}

::v-deep .el-card__body {
  padding: 0;
}
</style>
